<script setup>
import axios from "axios";
import {onMounted, ref} from "vue";

const name = ref('')
const list = ref([])
const entry = ref({})
const render = async () => {
  const {data: {data}} = await axios.get('http://127.0.0.1:8080')
  list.value = data
}
onMounted(() => {
  render()
})

const look = async () => {
  const {data: {data}} = await axios.get('http://127.0.0.1:8080/getPatch', {
    params: {name: name.value}
  })
  list.value = data
}

const del = async (id) => {
  console.log(id)
  await axios.delete('http://127.0.0.1:8080/delEntry', {
        params: {id}
      }
  )
  await render()
}

const update = async () => {
  const {id, name, tel, dept} = entry.value
  if (id) {
    isShow.value = false
    await axios.put('http://127.0.0.1:8080/updateEntry', {name, tel, dept}, {
      params: {id}
    })
    entry.value = {}
    await render()
  } else
    isShow.value = false
    await axios.post('http://127.0.0.1:8080/addEntry', {name, tel, dept})
  entry.value = {}
  await render()
}

const isShow = ref(false)
</script>

<template>

  <div>
    <input type="text" placeholder="输入关键字查询" v-model="name"/>
    <button @click="look">查询</button>
    <button @click="isShow = true">添加</button>
  </div>
  <div class="table">
    <table>
      <thead>
      <th>序号</th>
      <th>名字</th>
      <th>电话</th>
      <th>部门</th>
      <th>编辑</th>
      </thead>
      <tbody>
      <tr v-for="(item,index) in list" :key="item.id">
        <td>{{ item.id }}</td>
        <td>{{ item.name }}</td>
        <td>{{ item.tel }}</td>
        <td>{{ item.dept }}</td>
        <td>
          <button @click="isShow = true;entry.id = item.id">编辑</button>
          <button @click="del(item.id)">删除</button>
        </td>
      </tr>
      </tbody>
    </table>
  </div>

  <div class="tc" v-show="isShow">
    <div class="content">
      <label>名字</label>
      <input type="text" v-model="entry.name">
      <br>
      <label>电话</label>
      <input type="text" v-model="entry.tel">
      <br>
      <label>部门</label>
      <input type="text" v-model="entry.dept">
      <br>
      <button @click="isShow = false">取消</button>
      <button @click="update">确认</button>
    </div>
  </div>
</template>


<style scoped>
body {
  margin: 0 auto;
  padding: 0;
}

table {
  border: 2px black solid;
  border-collapse: collapse;
  text-align: center;
}

th, td {
  border: 1px black solid;
  border-collapse: collapse;
}

.tc {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(6, 6, 6, 6%);
}

.content {
  width: 300px;
  height: 100px;
  background-color: white;
  text-align: center;
  margin-left: 43%;
  margin-top: 23%;
}
</style>
